package com.doform.android.xianggucheng.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.signature.StringSignature;
import com.doform.android.xianggucheng.R;
import com.doform.android.xianggucheng.adapter.CommonListAdapter;
import com.doform.android.xianggucheng.bean.CategoryQueryBean;
import com.doform.android.xianggucheng.bean.CommonQueryBean;
import com.doform.android.xianggucheng.bean.GoodAllBean;
import com.doform.android.xianggucheng.bean.GoodBean;
import com.doform.android.xianggucheng.bean.Goods;
import com.doform.android.xianggucheng.bean.ImageBean;
import com.doform.android.xianggucheng.bean.UnitBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqImage;
import com.doform.android.xianggucheng.bean.request_bean.ReqListMeasureUnitBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqQueryArticle;
import com.doform.android.xianggucheng.bean.request_bean.ReqQueryArticlePrice;
import com.doform.android.xianggucheng.bean.request_bean.ReqQueryCategory;
import com.doform.android.xianggucheng.bean.request_bean.ReqQueryVendorBean2;
import com.doform.android.xianggucheng.bean.request_bean.ReqUpdateArticle;
import com.doform.android.xianggucheng.holder.ViewHolder;
import com.doform.android.xianggucheng.popwindow.CommonPopWindow;
import com.doform.android.xianggucheng.popwindow.IPopWindow;
import com.doform.android.xianggucheng.retrofit.HttpManager;
import com.doform.android.xianggucheng.retrofit.subscriber.ErrorHandleSubscriber;
import com.doform.android.xianggucheng.utils.BitMapUtil;
import com.doform.android.xianggucheng.utils.Constans;
import com.doform.android.xianggucheng.utils.TsUtils;
import com.doform.android.xianggucheng.widget.DividerItemDecoration;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.iwf.photopicker.PhotoPicker;

import static com.doform.android.xianggucheng.R.id.tv;
import static com.doform.android.xianggucheng.R.id.tv_category;


/**
 * Created by Administrator on 2017/5/12.
 */

public class UpdateGoodsActivity extends BaseTitleActivity {

    @BindView(R.id.tv_vendor)
    TextView tvVendor;//供应商

    @BindView(tv_category)
    TextView tvCategory;//所属分类

    @BindView(R.id.et_name)
    EditText etName;//商品名称

    @BindView(R.id.tv_module)
    TextView tvModule;//计量单位

    @BindView(R.id.et_cost_price)
    EditText etCost_price;//成本价

    @BindView(R.id.et_retail_price)
    EditText etRetail_price;//零售价

    @BindView(R.id.btn_submit)
    Button mSubmit;

    @BindView(R.id.ll)
    LinearLayout mLl;

    @BindView(R.id.btn_select_pic)
    Button mBtnSelectPic;

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    @BindView(R.id.tv_state)
    TextView tvState;//状态

    @BindView(R.id.rl_state)
    RelativeLayout rl_state;

    private String mName;//商品名称
    private String mVendorId;//供应商ID
    private String mCategoryFId;//分类Fid
    private String mCategoryName;//分类名称
    private String mCostTypeId;//成本ID
    private String costTypeName;//成本名称
    private String mCostPrice;//
    //    private String mRetailPrice;
    private String mMessureId;
    private String mMessureName;
    private String mArticleState;

    private List<CommonQueryBean> mVendorDatas = new ArrayList<>();
    private List<CategoryQueryBean> mCategoryDatas = new ArrayList<>();
    private List<UnitBean.DataBean> numDatas = new ArrayList<>();

    private IPopWindow mPopupWindow, mPopupWindow4, mPopupWindow5;
    private CommonPopWindow mPopupWindow2;
    private RecyclerView mCategoryRecyclerView;
    private String mId;

    private List<String> mPhotos = new ArrayList<>();

    private boolean isSelectedPhotos = true;

    private CommonAdapter<String> mCommonAdapter;

    private Goods.ListBean mBean;
    private String img;
    private String imgfile;
    private String mRetailPrice;

    @Override
    protected int layoutResId() {
        return R.layout.activity_new_and_update_goods;
    }

    @Override
    protected void init() {

        Goods.ListBean bean = (Goods.ListBean) getIntent().getSerializableExtra(Constans.EXTRA_UPDATE_ARTICLE);
        this.mBean = bean;


        if (mPopupWindow == null) {
            mPopupWindow = new IPopWindow(this, R.layout.pop_new_add_goodsk);
        }

        if (mPopupWindow2 == null) {
            mPopupWindow2 = new CommonPopWindow(this, R.layout.pop_goods_category);
        }

        if (mPopupWindow4 == null) {
            mPopupWindow4 = new IPopWindow(this, R.layout.pop_new_add_goodsk);
        }
        if (mPopupWindow5 == null) {
            mPopupWindow5 = new IPopWindow(this, R.layout.pop_new_add_goodsk);
        }
    }

    @Override
    protected void initView() {

        mCategoryRecyclerView = mPopupWindow2.getView(R.id.recyclerView);
        mCategoryRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mCategoryRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mCategoryRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

    }

    @Override
    protected void initData() {
        initVendorData();
        initCategoryData();
        initMeasureData();
        getDataForServiceAll();
    }


    @Override
    protected void initListener() {

        mCommonAdapter = new CommonAdapter<String>(this, R.layout.item_photos, mPhotos) {
            @Override
            protected void convert(com.zhy.adapter.recyclerview.base.ViewHolder holder, String s, final int position) {

                ImageView imageView = holder.getView(R.id.iv);
                CardView cardView = holder.getView(R.id.card_view);

                String reg = "[a-zA-z]+://[^\\s]*";
                Pattern pattern = Pattern.compile(reg);
                Matcher matcher = pattern.matcher(s);
                boolean b = matcher.matches();

                if (b) {
                    Glide.with(UpdateGoodsActivity.this)
                            .load(s)
                            .signature(new StringSignature(String.valueOf(System.currentTimeMillis())))
                            .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                            .into(imageView);
                } else {
                    Glide.with(UpdateGoodsActivity.this)
                            .load(Uri.fromFile(new File(s)))
                            .signature(new StringSignature(String.valueOf(System.currentTimeMillis())))
                            .into(imageView);

                    cardView.setOnClickListener(new View.OnClickListener() {
                                                    @Override
                                                    public void onClick(View v) {
                                                        new AlertDialog.Builder(UpdateGoodsActivity.this)
                                                                .setTitle("删除对话框")
                                                                .setMessage("确认不上传该图片？")
                                                                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(DialogInterface dialog, int which) {
                                                                                mPhotos.remove(position);
                                                                                notifyDataSetChanged();
                                                                                dialog.dismiss();
                                                                            }
                                                                        }
                                                                )
                                                                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(DialogInterface dialog, int which) {
                                                                                dialog.dismiss();
                                                                            }
                                                                        }
                                                                )
                                                                .create().show();
                                                    }
                                                }
                    );
                    imageView.setImageURI(Uri.fromFile(new File(s)));
                }
            }
        };
        mRecyclerView.setAdapter(mCommonAdapter);
    }


    private void getDataForServiceAll() {

        Observable
                .zip(getDataForService(), getPriceDataForService(), new BiFunction<ArrayList<GoodBean>, String, GoodAllBean>() {
                            @Override
                            public GoodAllBean apply(@NonNull ArrayList<GoodBean> goodBeen, @NonNull String s) throws Exception {
                                return new GoodAllBean(goodBeen, s);
                            }
                        }
                ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ErrorHandleSubscriber<GoodAllBean>() {
                    @Override
                    public void onNext(@NonNull GoodAllBean goodAllBean) {
                        parseData(goodAllBean.getData().get(0), goodAllBean.getPrice());
                    }
                })
        ;

    }

    /**
     * 获取商品数据
     *
     * @return
     */
    private Observable<ArrayList<GoodBean>> getDataForService() {
        return HttpManager
                .instance()
                .getArticleDetail(new ReqQueryArticle(mBean.getId(), mBean.getGuid()));
    }

    private Observable<String> getPriceDataForService() {
        return HttpManager
                .instance()
                .getArticle0Price(new ReqQueryArticlePrice(mBean.getId()));
    }

    private void parseData(GoodBean dataBean, String price) {
        mVendorId = dataBean.getSupplierid();
        tvVendor.setText(dataBean.getSuppliername());

        mCategoryFId = dataBean.getClslayerids();
        mCategoryName = dataBean.getClslayernames();
        tvCategory.setText(mCategoryName);

        mName = dataBean.getName();
        etName.setText(mName);

        mCostTypeId = dataBean.getCosttype();

        mMessureName = dataBean.getUnit();
        mMessureId = dataBean.getUnit_id();
        tvModule.setText(mMessureName);

        mCostPrice = dataBean.getCostprice();
        etCost_price.setText(mCostPrice);

        mRetailPrice = price;

        etRetail_price.setText(mRetailPrice);
        etRetail_price.requestFocus();

        etCost_price.requestFocus();
        etName.requestFocus();

        mArticleState = dataBean.getState();

        if (mArticleState.equals("0"))
            tvState.setText("下架");
        else if (mArticleState.equals("1")) {
            tvState.setText("上架");
        }

        img = dataBean.getImg();
        imgfile = dataBean.getImgfile();

        if (imgfile != null) {
            mPhotos.clear();
            String[] sourceStrArray = dataBean.getImgfile().split(",");
            for (int i = 0; i < sourceStrArray.length; i++) {
                mPhotos.add(sourceStrArray[i]);
                mCommonAdapter.notifyDataSetChanged();
            }
        }

    }

    @Override
    protected void showView() {
        titleBar.setTextTitle("修改商品");
    }

    @OnClick({R.id.tv_vendor, R.id.tv_category, R.id.tv_module, R.id.btn_submit, R.id.btn_select_pic, R.id.tv_state})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.tv_vendor:
                showVendorPop(mVendorDatas);
                break;
            case R.id.tv_category:
                showCategoryPop(mCategoryDatas);
                break;
            case R.id.tv_module:
                showMeasurePop(numDatas);
                break;
            case R.id.btn_submit:
                beforeSubmit();
                break;
            case R.id.btn_select_pic:
                pickPhoto();
                break;
            case R.id.tv_state:
                showSatePop();
                break;
            default:
                break;
        }
    }

    private void showSatePop() {
        List<String> states = new ArrayList<>();
        states.add("下架");
        states.add("上架");
        mPopupWindow5.setPopAdapter(new CommonListAdapter<String>(this, states, R.layout.pop_item) {
            @Override
            protected void convert(ViewHolder vh, final List<String> datas, final int position) {

                TextView tv_name = vh.getView(tv);
                tv_name.setText(datas.get(position));
                vh.getView(R.id.rl_select).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tvState.setText(datas.get(position));
                        if ("下架".equals(tvState.getText().toString())) {
                            mArticleState = "0";
                        } else mArticleState = "1";
                        mPopupWindow5.dismiss();
                    }
                });
            }
        });
        mPopupWindow5.showAtLocation(mLl, Gravity.BOTTOM, 0, 0);
    }

    private void pickPhoto() {
        PhotoPicker.builder()
                .setPhotoCount(6)
                .setShowCamera(true)
                .setShowGif(true)
                .setPreviewEnabled(true)
                .start(this, PhotoPicker.REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                mPhotos.clear();
                ArrayList<String> tempList = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                if (tempList.size() == 0) {
                    isSelectedPhotos = true;
                } else {
                    isSelectedPhotos = false;
                    mPhotos.addAll(tempList);
                    mCommonAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    private void beforeSubmit() {

        mName = etName.getText().toString().trim();
        mCostPrice = etCost_price.getText().toString().trim();
        mRetailPrice = etRetail_price.getText().toString().trim();

        if (TextUtils.isEmpty(mName)) {
            Toast.makeText(this, "请填写商品名称", Toast.LENGTH_SHORT).show();
            return;
        } else if (TextUtils.isEmpty(mCostPrice)) {
            Toast.makeText(this, "请填写商品成本价格", Toast.LENGTH_SHORT).show();
            return;
        } else if (TextUtils.isEmpty(mRetailPrice)) {
            Toast.makeText(this, "请填写商品零售价格", Toast.LENGTH_SHORT).show();
            return;
        } else if (TextUtils.isEmpty(mVendorId)) {
            Toast.makeText(this, "请选择供应商", Toast.LENGTH_SHORT).show();
            return;
        } else if (TextUtils.isEmpty(mCategoryFId)) {
            Toast.makeText(this, "请选择分类", Toast.LENGTH_SHORT).show();
            return;
        } else if (TextUtils.isEmpty(mMessureId)) {
            Toast.makeText(this, "请选择计量单位", Toast.LENGTH_SHORT).show();
            return;
        }

        if (isSelectedPhotos) {// 大神
            postDataToService(mBean.getId(), mBean.getGuid(), mName, mCategoryFId, mVendorId, mCostPrice,
                    mRetailPrice, mMessureName, mMessureId, img, imgfile,mArticleState)
                    .subscribe(new SubmitResultSubscriber2());
        } else {
            postBase64Bitmap();
        }

    }

    private Observable<String> postDataToService(String id, String guid, String mName, String mCategoryFId, String mVendorId,
                                                 String mCostPrice, String mRetailPrice, String mMessureName, String mMessureId,
                                                 String img, String imgfile,String mArticleState) {
        return HttpManager.instance()
                .updateArticle(new ReqUpdateArticle(id, guid, mName, mCategoryFId, mVendorId,
                        mCostPrice, mRetailPrice, mMessureName, mMessureId, img, imgfile,mArticleState));
    }

    private void postBase64Bitmap() {

        Observable.just(mPhotos)
                .subscribeOn(Schedulers.io())
                .map(new Function<List<String>, String[]>() {
                    @Override
                    public String[] apply(@NonNull List<String> strings) throws Exception {
                        String imgType = "";
                        String[] strArray = new String[strings.size()];
                        for (int i = 0; i < strings.size(); i++) {
                            if (strings.get(i).endsWith(".jpg")) {
                                imgType = "jpg";
                            } else if (strings.get(i).endsWith(".png")) {
                                imgType = "png";
                            } else if (strings.get(i).endsWith(".gif")) {
                                imgType = "gif";
                            } else {
                                TsUtils.showToast("请选择png/jpg/gif格式的图片");
                            }
                            strArray[i] = BitMapUtil.imgCompress(strings.get(i), 480, 800, 100, imgType);
                        }
                        return strArray;
                    }
                })
                .map(new Function<String[], String>() {
                         @Override
                         public String apply(@NonNull String[] strings) throws Exception {
                             return JSON.toJSONString(strings);
                         }
                     }
                )
                .flatMap(new Function<String, ObservableSource<ArrayList<ImageBean>>>() {
                             @Override
                             public ObservableSource<ArrayList<ImageBean>> apply(@NonNull String json) throws Exception {
                                 return HttpManager.instance()
                                         .postImg(new ReqImage(json));
                             }
                         }
                )
                .flatMap(new Function<ArrayList<ImageBean>, ObservableSource<String>>() {
                             @Override
                             public ObservableSource<String> apply(@NonNull ArrayList<ImageBean> data) throws Exception {

                                 String imgId = "";
                                 String imgFilesName = "";
                                 for (int i = 0; i < data.size(); i++) {
                                     if (i == data.size() - 1) {
                                         imgId = imgId + data.get(i).getId();
                                         imgFilesName = imgFilesName + data.get(i).getUrl();
                                     } else {
                                         imgId = imgId + data.get(i).getId() + ",";
                                         imgFilesName = imgFilesName + data.get(i).getUrl() + ",";
                                     }
                                 }
                                 return postDataToService(mBean.getId(), mBean.getGuid(), mName, mCategoryFId, mVendorId, mCostPrice,
                                         mRetailPrice, mMessureName, mMessureId, imgId, imgFilesName,mArticleState);
                             }
                         }
                )
                .subscribe(new SubmitResultSubscriber2());

    }

    public void showVendorPop(List<CommonQueryBean> datas) {

        mPopupWindow.setHeadName("添加供应商");

        mPopupWindow.setHeadListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(UpdateGoodsActivity.this, NewVendorActivity.class));
            }
        });
        mPopupWindow.setPopAdapter(new CommonListAdapter<CommonQueryBean>(this, datas, R.layout.pop_category_item2) {
            @Override
            protected void convert(ViewHolder vh, final List<CommonQueryBean> datas, final int position) {
                final CommonQueryBean dataBean = datas.get(position);

                TextView tvVendor = vh.getView(tv);
                tvVendor.setText(dataBean.getName());
                vh.getView(R.id.rl_select).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        UpdateGoodsActivity.this.tvVendor.setText(dataBean.getName());
                        mVendorId = dataBean.getId();
                        mPopupWindow.dismiss();
                    }
                });
            }
        });
        mPopupWindow.showAtLocation(mLl, Gravity.BOTTOM, 0, 0);
    }


    public void showCategoryPop(final List<CategoryQueryBean> datas) {

        CommonAdapter mCategoryItemCateAdapter = new CommonAdapter<CategoryQueryBean>(this, R.layout.pop_category_item2, datas) {
            @Override
            protected void convert(com.zhy.adapter.recyclerview.base.ViewHolder holder, CategoryQueryBean listBean, int position) {
                TextView tv_name = holder.getView(R.id.tv);
                TextView tv_name2 = holder.getView(R.id.tv2);
                if (listBean.getLv() == 2) {//二级
                    tv_name2.setText(listBean.getName());
                } else if (listBean.getLv() == 1) {
                    tv_name.setText(listBean.getName());
                } else {
                }
            }
        };

        mCategoryItemCateAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                CategoryQueryBean bean = datas.get(position);

                mCategoryFId = "";

                if (bean.getLv() == 1) {
                    mCategoryFId = bean.getId();
                } else if (bean.getLv() == 2) {
                    mCategoryFId = bean.getFid() + "," + bean.getId();
                } else {
                }
                mCategoryName = bean.getName();
                tvCategory.setText(mCategoryName);
                mPopupWindow2.dismiss();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        mCategoryRecyclerView.setAdapter(mCategoryItemCateAdapter);
//
        mPopupWindow2.showAtLocation(mLl, Gravity.BOTTOM, 0, 0);
    }


    public void showMeasurePop(List<UnitBean.DataBean> datas) {
        mPopupWindow4.setGoneHeadView();
        mPopupWindow4.setPopAdapter(new CommonListAdapter<UnitBean.DataBean>(this, datas, R.layout.pop_item) {
            @Override
            protected void convert(ViewHolder vh, final List<UnitBean.DataBean> datas, final int position) {

                final UnitBean.DataBean messBean = datas.get(position);

                TextView tv_name = vh.getView(tv);
                tv_name.setText(messBean.getName());
                vh.getView(R.id.rl_select).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tvModule.setText(messBean.getName());
                        mMessureName = messBean.getName();
                        mMessureId = messBean.getId();
                        mPopupWindow4.dismiss();
                    }
                });
            }
        });
        mPopupWindow4.showAtLocation(mLl, Gravity.BOTTOM, 0, 0);
    }

    /**
     * 计算单位
     */
    private void initMeasureData() {
        HttpManager.instance()
                .getMeasureUnit(new ReqListMeasureUnitBean("1"))
                .subscribe(new ErrorHandleSubscriber<UnitBean>() {
                    @Override
                    public void onNext(@NonNull UnitBean unitBean) {
                        numDatas.addAll(unitBean.getList());
                    }
                });
    }


    /**
     * 分类数据
     */
    private void initCategoryData() {
        HttpManager.instance()
                .getCategoryQuery2(new ReqQueryCategory())
                .subscribe(new ErrorHandleSubscriber<ArrayList<CategoryQueryBean>>() {
                    @Override
                    public void onNext(@NonNull ArrayList<CategoryQueryBean> categoryBean) {
                        mCategoryDatas.addAll(categoryBean);
                    }
                });
    }

    /**
     * 供应商数据
     */
    private void initVendorData() {

        HttpManager
                .instance()
                .getVendorQuery2(new ReqQueryVendorBean2())
                .subscribe(new ErrorHandleSubscriber<ArrayList<CommonQueryBean>>() {
                               @Override
                               public void onNext(@NonNull ArrayList<CommonQueryBean> vendorBean) {
                                   mVendorDatas.addAll(vendorBean);
                               }
                           }
                );
    }


}
